package com.das.mechanic_base.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;

import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;

public class X3NetUtils {

    private static boolean result;

    /**
     * 获取当前信号强度
     * 0 无网络
     * 1 网络差
     * 2 网络较好
     * 3 网络好
     * @param context
     * @return
     */
    public static int getNetWorkType(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            String type = networkInfo.getTypeName();
            if (type.equalsIgnoreCase("WIFI")) {
                return getWifiStrength(context);
            } else if (type.equalsIgnoreCase("MOBILE")) {
                if (!hasSimCard(context)) {
                    return 1;
                }
                return 2;

            }
        }
        return 0;
    }

    private static int getWifiStrength(Context mContext) {
        WifiManager mWifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
        WifiInfo mWifiInfo = mWifiManager.getConnectionInfo();
        int wifi = mWifiInfo.getRssi();//获取wifi信号强度
        if (wifi > -50 && wifi < 0) {//最强
            return 3;
        } else if (wifi > -80 && wifi < -50) {//较强
            return 2;
        }
        return 1;
    }

    /**
     * 判断是否包含SIM卡
     *
     * @return 状态
     */
    private static boolean hasSimCard(Context context) {
        result = true;
        XXPermissions.with(context)
                .permission(Permission.READ_PHONE_STATE,Permission.READ_PHONE_NUMBERS)
                .request((permissions, all) -> {
                    TelephonyManager telMgr = (TelephonyManager)
                            context.getSystemService(Context.TELEPHONY_SERVICE);
                    int simState = telMgr.getSimState();

                    switch (simState) {
                        case TelephonyManager.SIM_STATE_ABSENT:
                        case TelephonyManager.SIM_STATE_UNKNOWN:
                            result = false; // 没有SIM卡
                            break;
                    }
                });

        return result;
    }

}
